package com.ibm.mall.action;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ibm.mall.base.BaseAction;
import com.ibm.mall.model.CarBean;
import com.ibm.mall.model.Commodity;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
public class CustomerCarAction extends BaseAction<Commodity> {

	private static final long serialVersionUID = 1L;
	
	private Integer commodityId;
	
	private Map session;
	
	@SuppressWarnings("unchecked")
	public String addToCar() {
		Commodity commodity=commodityService.getCommodityById(commodityId);
		Map<Integer,CarBean> car=null;
		session=ActionContext.getContext().getSession();
		if(ActionContext.getContext().getSession().get("car")==null){
			car=new HashMap<Integer,CarBean>();
		}else{
			car=(Map<Integer,CarBean>) ActionContext.getContext().getSession().get("car");
		}
		if(car.containsKey(commodity.getId())){
			car.get(commodity.getId()).setCount(car.get(commodity.getId()).getCount()+1);
		}else{
			CarBean carBean=new CarBean();
			carBean.setCommodity(commodity);
			carBean.setCount(1);
			car.put(commodity.getId(), carBean);
		}
		session.put("car", car);
		Integer carSize=0;
		for (Entry<Integer, CarBean> entry : car.entrySet()) {
			carSize+=entry.getValue().getCount();
		}
		session.put("carSize", carSize);
		Double totalPrice=0.0;
		for (Entry<Integer, CarBean> entry : car.entrySet()) {
			totalPrice=totalPrice+entry.getValue().getCount()*entry.getValue().getCommodity().getCommodityPrice();
		}
		session.put("totalPrice", totalPrice);
		return "success";
	}
	
	@SuppressWarnings("unchecked")
	public String deleteFromCar() {
		session=ActionContext.getContext().getSession();
		Map<Integer,CarBean> car=(Map<Integer,CarBean>) session.get("car");
		car.remove(commodityId);
		ActionContext.getContext().getSession().put("car", car);
		Integer carSize=0;
		for (Entry<Integer, CarBean> entry : car.entrySet()) {
			carSize+=entry.getValue().getCount();
		}
		session.put("carSize", carSize);
		Double totalPrice=0.0;
		for (Entry<Integer, CarBean> entry : car.entrySet()) {
			totalPrice=totalPrice+entry.getValue().getCount()*entry.getValue().getCommodity().getCommodityPrice();
		}
		session.put("totalPrice", totalPrice);
		return "success";
	}
	
	public String showCar() {
		return "success";
	}

	public Integer getCommodityId() {
		return commodityId;
	}

	public void setCommodityId(Integer commodityId) {
		this.commodityId = commodityId;
	}

	public Map getSession() {
		return session;
	}

	public void setSession(Map session) {
		this.session = session;
	}
	
	

}
